package com.vietnam.power.dao.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.vietnam.power.constant.AppConfigurationConstant;
import com.vietnam.power.dao.FileDao;
import com.vietnam.power.domain.FileSearchCriteria;
import com.vietnam.power.persitence.FileUpload;

@Repository
@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
public class FileDaoImpl extends GenericDaoImpl implements FileDao {

	@Transactional(readOnly = true)
	public FileUpload getFileById(int id) {
		return findById(FileUpload.class, id);
	}

	@SuppressWarnings("unchecked")
	public List<FileUpload> getFilesByName(String fileName) {
		Criteria crt = getSessionFactory().getCurrentSession().createCriteria(FileUpload.class);

		crt.add(Restrictions.eq("name", fileName));
		crt.add(Restrictions.eq("status", Boolean.TRUE));
		return crt.list();
	}

	public void saveFile(FileUpload f) {
		save(f);
	}

	public void updateFile(FileUpload f) {
		merge(f);
	}

	public void deleteFile(FileUpload f) {
		delete(f);
	}

	public long countFilesInGroup(String fileName) {
		Criteria crt = getSessionFactory().getCurrentSession().createCriteria(FileUpload.class);

		crt.add(Restrictions.eq("name", fileName));
		crt.add(Restrictions.eq("status", Boolean.TRUE));
		return (Long) crt.setProjection(Projections.rowCount()).uniqueResult();
	}

	@SuppressWarnings("unchecked")
	public List<FileUpload> searchFiles(FileSearchCriteria s) {
		Criteria crt = getSessionFactory().getCurrentSession().createCriteria(FileUpload.class);
		if (StringUtils.isNotBlank(s.getName())) {
			crt.add(Restrictions.eq("name", s.getName()));
		}

		crt.add(Restrictions.disjunction().add(Restrictions.eq("name", AppConfigurationConstant.FILE_UPLOAD.FILE_ADVERTISING_NAME))
				.add(Restrictions.eq("name", AppConfigurationConstant.FILE_UPLOAD.FILE_BANNER_NAME))
				.add(Restrictions.eq("name", AppConfigurationConstant.FILE_UPLOAD.FILE_SLIDER_NAME))
				.add(Restrictions.eq("name", AppConfigurationConstant.FILE_UPLOAD.FILE_FOOTER_NAME)));
		crt.add(Restrictions.eq("status", Boolean.TRUE));
		return crt.list();
	}

	@SuppressWarnings("unchecked")
	public List<FileUpload> getUnusedFiles() {
		Criteria crt = getSessionFactory().getCurrentSession().createCriteria(FileUpload.class);
		crt.add(Restrictions.eq("status", Boolean.FALSE));
		return crt.list();
	}
}
